package com.customization.unionpay.market.workflowaction;

import com.alibaba.fastjson.JSONObject;
import com.api.integration.BaseBean;
import com.customization.unionpay.contract.serivce.IContractBaseService;
import com.customization.unionpay.contract.serivce.impl.ContractBaseServiceImpl;
import com.customization.unionpay.market.dao.MarketAdvanceCtrlDao;
import com.customization.unionpay.market.dao.MarketAdvancePayCheckDao;
import com.customization.unionpay.market.maketEnum.InstructionEnum;
import com.customization.unionpay.market.service.impl.MarketAdvancePayCheckWorkflowServiceImpl;
import com.customization.unionpay.market.util.FormDataUtils;
import com.customization.unionpay.market.util.FormUtil;
import weaver.generalledger.action.ZzgdExecuteInstrucitonAction;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.OverTimeSetBean;
import weaver.workflow.request.RequestManager;

import java.util.List;
import java.util.Map;

public class MarketAdvancePayCheckAction extends BaseBean implements Action {

    private static final Logger log = LoggerFactory.getLogger(MarketAdvancePayCheckAction.class);

    @Override
    public String execute(RequestInfo requestInfo) {
        try {
            RequestManager rm = requestInfo.getRequestManager();
            OverTimeSetBean overTimeSetBean = new OverTimeSetBean();
            String loginid = rm.getUser().getLoginid();
            int nodeId = rm.getNodeid();
            int requestid = rm.getRequestid();
            String nodeName = overTimeSetBean.getNodeName(nodeId);
            String src = rm.getSrc();
            int formId = rm.getFormid();
            String tableName = rm.getBillTableName();
            //获取主笔明细
            Map<String, Object> tableInfo = com.customization.unionpay.market.util.FormDataUtils.getMainFormData(requestInfo);
            String xmbh = tableInfo.get("project_code").toString();
            List<Map<String, Object>> detailInfo = com.customization.unionpay.market.util.FormDataUtils.getDetailFormDataByIndex(0, requestInfo);
            com.customization.unionpay.market.dao.MarketAdvancePayCheckDao marketAdvancePayCheckDao = new MarketAdvancePayCheckDao();
            IContractBaseService contractBaseService = new ContractBaseServiceImpl();
            com.customization.unionpay.market.service.impl.MarketAdvancePayCheckWorkflowServiceImpl marketAdvancePayCheckService
                    = new MarketAdvancePayCheckWorkflowServiceImpl();
            List<JSONObject> list = marketAdvancePayCheckService.checkBudget("ZX", requestInfo);
            //判断是否为大协议
            if ("结束".equals(nodeName)) {
                String sfwdxyId = tableInfo.get("sfwdxy").toString();
                String sfwdxyName = com.customization.unionpay.market.util.FormDataUtils.getItemName(formId, "sfwdxy", sfwdxyId);

                if ("否".equals(sfwdxyName)) {


//                    Map<String, Object> params = new HashMap<>();
//                    params.put("params", list);
//                    Map<String, Object> otherMap = new HashMap<>();
//                    otherMap.put("logId", requestid);
//                    otherMap.put("user", loginid);
//                    Map<String, Object> verify = businessBudgetService.verify(params, otherMap);
//                    JSONArray arr = JSONArray.parseArray(verify.get("result").toString());
//                    String status = arr.getJSONObject(0).getString("status");
//                    String status = "1";
//                    if ("1".equals(status)) {
//                        businessBudgetService.execBudget(params, otherMap);
//                        String fplx = FormDataUtils.getItemName(FormUtil.MARKET_ADVANCE_PAY_CHECK_ID, "fplx", tableInfo.get("fplx").toString());
//                        if ("增值税发票".equals(fplx)) {
//                            for (int i = 0; i < detailInfo.size() && i < list.size(); i++) {
//                                Map<String, Object> detail = detailInfo.get(i);
//                                if (detail.containsKey("bzse")) {
//                                    Double bzse = Double.parseDouble(detail.get("bzse").toString());
//                                    JSONObject jsonObject = list.get(i);
//                                    jsonObject.put("amount", bzse/1000);
//                                    jsonObject.put("instruction", "SFZY");
//                                }
//                                businessBudgetService.execBudget(params, otherMap);
//                            }
//                            //todo:控制表调用预算占用
//                            MarketAdvanceCtrlDao marketAdvanceCtrlDao = new MarketAdvanceCtrlDao();
//                            for (JSONObject o : list) {
//                                marketAdvanceCtrlDao.insert(o,requestid);}
//                            params.put("params", list);
//                            businessBudgetService.execBudget(params, otherMap);
//                        }

                    String instruction = com.customization.unionpay.market.maketEnum.InstructionEnum.SFZYQZX.toString();
                    MarketAdvanceCtrlDao marketAdvanceCtrlDao = new MarketAdvanceCtrlDao();
                    for (JSONObject o : list) {
                        boolean result = marketAdvanceCtrlDao.insert(o, requestid, tableName);
                        if (!result) {
                            log.error("插入失败");
                            return Action.FAILURE_AND_CONTINUE;
                        }
                    }
                    log.info("插入成功");
                    ZzgdExecuteInstrucitonAction zzgdExecuteInstrucitonAction = new ZzgdExecuteInstrucitonAction();
                    zzgdExecuteInstrucitonAction.setZl(instruction);
                    String execute = zzgdExecuteInstrucitonAction.execute(requestInfo);
                    log.info(execute);
                    if ("0".equals(execute)) {
                        String messageid = requestInfo.getRequestManager().getMessageid();
                        log.info("messageid：" + messageid);
                        String messagecontent = requestInfo.getRequestManager().getMessagecontent();
                        log.info("messagecontent：" + messagecontent);
                        return Action.FAILURE_AND_CONTINUE;
                    } else {
                        log.info("预算执行调用成功！");
                    }


                    String fplx = FormDataUtils.getItemName(FormUtil.MARKET_ADVANCE_PAY_CHECK_ID, "fplx", tableInfo.get("fplx").toString());
                    if ("增值税发票".equals(fplx)) {
                        for (int i = 0; i < detailInfo.size() && i < list.size(); i++) {
                            Map<String, Object> detail = detailInfo.get(i);
                            Double bzse = Double.parseDouble(detail.get("bzse").toString());
                            if (bzse != 0) {
                                JSONObject jsonObject = list.get(i);
                                jsonObject.put("amount", bzse / 1000);
                                boolean result = marketAdvanceCtrlDao.insert(jsonObject, requestid, tableName);
                                if (!result) {
                                    log.error("插入失败");
                                    return Action.FAILURE_AND_CONTINUE;
                                }
                            }
                        }
                    }
                    log.info("数据已插入中间表");
                    String instruction1 = InstructionEnum.SFZX.toString();
                    zzgdExecuteInstrucitonAction.setZl(instruction1);
                    String execute1 = zzgdExecuteInstrucitonAction.execute(requestInfo);
                    log.info(execute1);
                    if ("0".equals(execute1)) {
                        String messageid = requestInfo.getRequestManager().getMessageid();
                        log.info("messageid：" + messageid);
                        String messagecontent = requestInfo.getRequestManager().getMessagecontent();
                        log.info("messagecontent：" + messagecontent);
                        return Action.FAILURE_AND_CONTINUE;
                    } else {
                        log.info("报账税额释放占用调用成功！");
                    }
                    //流程提交时【本次核销合同计提金额】扣减合同【计提余额】
//                    for (int i = 0; i < detailInfo.size(); i++) {
//                        Map<String, Object> detail = detailInfo.get(i);
//                        if (detail.containsKey("bchxhtjtje") && detail.containsKey("jtye")) {
////                            Double bchxhtjtje = Double.parseDouble(detail.get("bchxhtjtje").toString());
//                            int lymxh = Integer.parseInt(detail.get("lymxh").toString());
//                            String bchxhtjtje = detail.get("bchxhtjtje").toString();
//                            if (bchxhtjtje != null && lymxh != 0) {
//                                contractBaseService.updateLZJE(1, lymxh, bchxhtjtje);
//                            } else {
//                                log.error("金额扣减失败");
//                            }
//                        } else {
//                            log.error("明细表字段信息有误");
//                        }
//                    }
                } else {
                }
            }
//            if ("结束".equals(nodeName)) {
//                //流程归档时，报账金额写入【列账金额】
//                for (int i = 0; i < detailInfo.size(); i++) {
//                    Map<String, Object> detail = detailInfo.get(i);
//                    if (detail.containsKey("bzje")) {
////                        Double bzje = Double.parseDouble(detail.get("bzje").toString());
//                        int lymxh = Integer.parseInt(detail.get("lymxh").toString());
//                        String bzje = detail.get("bzje").toString();
//                        if (bzje != null && lymxh != 0) {
//                            contractBaseService.updateLZJE(3, lymxh, bzje);
//                        }
//                    }
//                }
//            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("预付款核销单流程提交失败", e);
        }
        return Action.SUCCESS;
    }
}
